package com.kmproject.haifu.app.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;


import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.mvp.ui.activity.NoticeRentSeekingActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "ehome";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            printBundle(bundle);
            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                receiverMessage(bundle);
            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                clickMessage(bundle,context);
            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {


            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {

            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    /**
     * 点击通知
     * @param bundle
     */
      public void clickMessage(Bundle bundle,Context context){

          Intent intent=null;
          String message = bundle.getString(JPushInterface.EXTRA_ALERT);
          if (bundle.getString(JPushInterface.EXTRA_EXTRA) == null || bundle.getString(JPushInterface.EXTRA_EXTRA).length() < 1) {
              return;
          }

//          if (AppUtil.mactivity.getClass().getName().equals(HomeActivity.class.getName()) && AppUtil.isForeground(context, HomeActivity.class.getName())) {
//            //homeactivty在最前面，并且在前台，不做任何处理
//              return;
//          }
              //打开自定义的Activity
          intent = new Intent(context, NoticeRentSeekingActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          context.startActivity(intent);
      }
    /**
     * 接收到消息
     */
    public void receiverMessage(Bundle bundle) {
        int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
        String message = bundle.getString(JPushInterface.EXTRA_ALERT);
        if (bundle.getString(JPushInterface.EXTRA_EXTRA) == null || bundle.getString(JPushInterface.EXTRA_EXTRA).length() < 1) {
            return;
        }
//        JpusMessage jpusMessage = new Gson().fromJson(bundle.getString(JPushInterface.EXTRA_EXTRA), JpusMessage.class);
//        if ("sysmessage".equals(jpusMessage.getMsgType()))
//        {
//            //系统推送消息，不发通知
//            return;
//        }

        EventBus.getDefault().post(new JPushMessage());
    }

}
